import Vue from 'vue'
import Vuex from 'vuex'
import moment from 'moment';


import infinitePowerSupply from '../assets/img/infinitePowerSupply.png'
import pvGeneration from '../assets/img/pvGeneration.png'
import fan from '../assets/img/fan.png'
import thermalPower from '../assets/img/thermalPower.png'
import pcs from '../assets/img/pcs.png'
import esBattery from '../assets/img/esBattery.png'
import threeWindingTransformer from '../assets/img/threeWindingTransformer.png'
import acBreaker from '../assets/img/acBreaker.png'
import dcBreaker from '../assets/img/dcBreaker.png'
import acBus from '../assets/img/acBus.png'
import dcBus from '../assets/img/dcBus.png'
import esAlternativeNode from '../assets/img/esAlternativeNode.png'
import crossPoint from '../assets/img/crossPoint.png'
import {createUUID} from "../utils/tools";
import {saveFileService, saveMatlabFileService} from "../service/indexService";


Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    operation: [
      {
        name: '文件',
        key: 'operation-1',
        icon: 'ios-document',
        children: [
          {
            name: '打开',
          },
          {
            name: '新建工程',
            event: 'createProject',
          },
          {
            name: '新建文件',
            event: 'createFile',
          },
          {
            name: '保存文件',
            event: 'saveFile'
          },
          {
            name: '保存matlab文件',
            event: 'saveMatlabFile'
          },
          {
            name: '关闭工程',
          },
        ]
      },
      {
        name: '功能',
        key: 'operation-2',
        icon: 'ios-hammer',
        children: [{
          name: '开启图表',
          event: 'openPlot'
        },{
          name: '关闭图表',
          event: 'closePlot'
        },{
          name: '开启3D示意图',
          event: 'openThree'
        },{
          name: '关闭3D示意图',
          event: 'closeThree'
        },  {
          name: '储能电站容量规划',
        }, {
          name: '光伏电站投资收益',
        }, {
          name: '电站运行模式规划',
        }, {
          name: '电站投资收益分析',
        },
        ]
      },
      {
        name: '工程',
        key: 'operation-3',
        icon: 'md-grid',
        children: [
          {
            name: 'group_1',
            type: 'group',
            groupName: '工程信息',
            children: [
              {
                name: '地理信息',
              }, {
                name: '资源信息',
              }
            ]
          },
          {
            name: 'group_2',
            type: 'group',
            groupName: '优化选项',
            children: [
              {
                name: '仿真时间',
              }, {
                name: '求解器',
              }, {
                name: '边界条件',
              }, {
                name: '敏感性分析',
              },
            ]
          },
        ]
      },
      {
        name: '放置',
        key: 'operation-4',
        icon: 'md-hand',
        children: [
          {
            name: 'group_3',
            type: 'group',
            groupName: '电网类',
            children: [
              {
                name: '电网组件',
                event: 'openTools',
                tools: [
                  {key: '无穷大电源', source: infinitePowerSupply},
                ],
              }
            ]
          },
          {
            name: 'group_4',
            type: 'group',
            groupName: '设备类',
            children: [
              {
                name: '发电组件',
                event: 'openTools',
                tools: [
                  {key: '火力发电', source: thermalPower},
                  {key: '光伏', source: pvGeneration},
                  {key: '风力发电', source: fan},
                ],
              },
              {
                name: '负荷组件',
                event: 'openTools',
                tools: [
                  {key: '火力发电', source: thermalPower},
                  {key: '光伏', source: pvGeneration},
                  {key: '风力发电', source: fan},
                ],
              },
              {
                name: '储能组件',
                event: 'openTools',
                tools: [
                  {key: '储能变流器', source: pcs},
                  {key: '储能电池', source: esBattery},
                ],
              },
              {
                name: '输配组件',
                event: 'openTools',
                tools: [
                  {key: '三绕组变压器', source: threeWindingTransformer},
                  {key: '交流断路器', source: acBreaker},
                  {key: '直流断路器', source: dcBreaker},
                ],
              }
            ]
          },
          {
            name: 'group_5',
            type: 'group',
            groupName: '节点类',
            children: [
              {
                name: '备选节点',
                event: 'openTools',
                tools: [
                  {key: '储能备选节点', source: esAlternativeNode},
                ],
              }
            ]
          },
          {
            name: 'group_6',
            type: 'group',
            groupName: '连接类',
            children: [
              {
                name: '输电线',
                event: 'openTools',
                tools: [
                  {key: '交流母线', source: acBus},
                  {key: '直流母线', source: dcBus},
                  {key: '交叉点', source: crossPoint},
                ],
              },
            ]
          },
        ]
      },
      {
        name: '运行',
        key: 'operation-5',
        icon: 'ios-bug',
        children: [
          {
            name: '开始仿真',
          },
          {
            name: '规划分析',
          },
        ]
      },
      {
        name: '结果',
        key: 'operation-6',
        icon: 'md-flask',
        children: [
          {
            name: '储能容量',
          },
          {
            name: '选址布点',
          },
          {
            name: '投资收益',
          },
          {
            name: '运行模式',
          },
        ]
      },
      {
        name: '帮助',
        key: 'operation-7',
        icon: 'md-help-circle',
        children: [
          {
            name: '主题',
            event: 'openTools',
            tools: [
              {key: '无穷大电源', source: thermalPower},
              {key: '光伏', source: pvGeneration},
              {key: '风力发电', source: fan},
            ],
          },
          {
            name: '版本',
          },
        ]
      },
    ],
    // 全部工具集 以及其相关数据，在这里注册了才能放到画布上
    toolsContent: {
      '无穷大电源': {
        key: '无穷大电源',
        source: infinitePowerSupply,
        simulation: function () {
          console.log('无穷大电源')
        }.toString()
      },
      '火力发电': {
        key: '火力发电',
        source: thermalPower,
        simulation: function () {
          console.log('火力发电')
        }.toString()},
      '光伏': {
        key: '光伏',
        source: pvGeneration,
        simulation: function () {
          console.log('光伏')
        }.toString()},
      '风力发电': {
        key: '风力发电',
        source: fan,
        simulation: function () {
          console.log('风力发电')
        }.toString()},
      '储能变流器': {
        key: '储能变流器',
        source: pcs,
        simulation: function () {
          console.log('储能变流器')
        }.toString()},
      '储能电池': {
        key: '储能电池',
        source: esBattery,
        simulation: function () {
          console.log('储能电池')
        }.toString()},
      '三绕组变压器': {
        key: '三绕组变压器',
        source: threeWindingTransformer,
        simulation: function () {
          console.log('三绕组变压器')
        }.toString()},
      '交流断路器': {
        key: '交流断路器',
        source: acBreaker,
        simulation: function () {
          console.log('交流断路器')
        }.toString()},
      '直流断路器': {
        key: '直流断路器',
        source: dcBreaker,
        simulation: function () {
          console.log('直流断路器')
        }.toString()},
      '储能备选节点': {
        key: '储能备选节点',
        source: esAlternativeNode,
        simulation: function () {
          console.log('储能备选节点')
        }.toString()},
      '交叉点': {
        key: '交叉点',
        source: crossPoint,
        simulation: function () {
          console.log('交叉点')
        }.toString()},
      '交流母线': {
        key: '交流母线',
        source: acBus,
        simulation: function () {
          console.log('交流母线')
        }.toString()},
      '直流母线': {
        key: '直流母线',
        source: dcBus,
        simulation: function () {
          console.log('直流母线')
        }.toString()},
    },
    showTools: false,
    showProperty: false,
    showPropertyInfinitePowerSupply: false,
    showPropertyPcs: false,
    showPropertyEsBattery: false,
    showPropertyThreeWindingTransformer: false,
    showPropertyAcBreaker: false,
    showPropertyDcBreaker: false,
    showPropertyEsAlternativeNode: false,
    showPropertyCrossPoint: false,
    showPropertyAcBus: false,
    showPropertyDcBus: false,

    curTools: [],
    //////////////////////////////////////////////////////
    treeSource: [
      {
        title: '测试工程',
        expand: true,
        uuid: '123123123',
        render(h, {root, node, data}) {
          return h('span', {
            style: {
              display: 'inline-block',
              width: '100%'
            }
          }, [
            h('span', [
              h('Icon', {
                props: {
                  type: 'ios-folder-outline'
                },
                style: {
                  marginRight: '8px'
                }
              }),
              h('span', data.title)
            ]),
            h('span', {
              style: {
                display: 'inline-block',
                float: 'right',
                marginRight: '32px'
              }
            })
          ]);
        },
        children: [
          {
            title: '文件1',
            uuid: 'asdfasdfa-asdf-asdf-23424'
          }
        ]
      }
    ],
    treeContent: {
      '123123123': {
        type: 'folder',
      },
      'asdfasdfa-asdf-asdf-23424': {
        type: 'file',
        nodeDataArray: [],
        linkDataArray: [],
      }
    },
    //////////////////////////////////////////////////////
    // 树形图选中项的内容值
    selectedUUID: '',
    selectedNodeKey: '',
    nodeDataArray: [
      // {key: '火力发电', source: thermalPower},
      // {key: '光伏', source: pvGeneration},
      // {key: '风力发电', source: fan},
    ],
    linkDataArray: [],
    nodeProperty: {
      // 对应文件下 对应节点
      'asdfasdfa-asdf-asdf-23424': {}

    },
    modelData: {
      canRelink: true
    },
    operationLog: [],
    configurationMode: 'index' // 组态区域显示标志， 默认index 显示绘制区域，plot 显示图表区
  },
  getters: {},
  mutations: {
    openTools(state, tools) {
      state.curTools = tools;
      state.showTools = true;
    },
    closeTools(state) {
      state.showTools = false;
    },
    createProject(state, title) {
      let uuid = createUUID();
      state.treeSource.push(
        {
          title,
          uuid,
          expand: true,
          render(h, {root, node, data}) {
            return h('span', {
              style: {
                display: 'inline-block',
                width: '100%'
              }
            }, [
              h('span', [
                h('Icon', {
                  props: {
                    type: 'ios-folder-outline'
                  },
                  style: {
                    marginRight: '8px'
                  }
                }),
                h('span', data.title)
              ]),
              h('span', {
                style: {
                  display: 'inline-block',
                  float: 'right',
                  marginRight: '32px'
                }
              })
            ]);
          },
          children: []
        }
      );
      state.treeContent[uuid] = {
        type: 'folder',
      }
    },
    createFile(state, title) {
      let uuid = createUUID();
      let selectedUUID = state.selectedUUID;

      let [curProject] = state.treeSource.filter(
        item => item.uuid === selectedUUID
      )
      curProject.children.push(
        {
          title,
          uuid
        }
      )
      state.treeContent[uuid] = {
        type: 'file',
        nodeDataArray: [],
        linkDataArray: [],
      }
      state.nodeProperty[uuid] = {}
    },
    selectTreeContent(state, uuid) {
      let {linkDataArray, nodeDataArray, selectedUUID, treeContent} = state;
      if (selectedUUID) {
        let pre = {...treeContent[selectedUUID]};
        if (treeContent[uuid] && treeContent[uuid].type === 'file') {
          treeContent[selectedUUID] = Object.assign(pre, {
            nodeDataArray,
            linkDataArray,
          })
        }
      }


      if (treeContent[uuid] && treeContent[uuid].type === 'file') {
        // 点击是文件 需要取出文件内容，保存之前内容
        state.nodeDataArray = treeContent[uuid] ? treeContent[uuid].nodeDataArray : [];
        state.linkDataArray = treeContent[uuid] ? treeContent[uuid].linkDataArray : [];
      }

      state.selectedUUID = uuid;

    },
    resetCanvas(state) {
      state.nodeDataArray = [];
      state.linkDataArray = [];
      state.modelData = {
        canRelink: true
      };
    },
    addElementToCanvas(state, element) {
      const {selectedUUID} = state;
      let key = element.key;
      let nodeData = {...element};
      let exit = state.nodeDataArray.filter(curItem =>
        curItem.key.indexOf(key) !== -1
      )
      if (exit.length > 0) {
        // 当前key已存在 需要自增key数字
        let n = exit[exit.length - 1].key.replace(key, '')
        if (n.length) {
          nodeData.key = `${key}${parseInt(n) + 1}`
        } else {
          nodeData.key = `${key}1`
        }

      }
      state.nodeDataArray.push(nodeData);
      //属性结构体定义同时给出设置页面控件初始值
      state.nodeProperty[selectedUUID][nodeData.key] = {
        field1: nodeData.key,
        field2: '',
        field3: '',
        field4: '',
        field5: '',
        field6: '',
        field7: '',
        field8: '',
        field9: '',
        field10: ''
      }
    },
    linkElementToOther(state, linkData) {
      state.linkDataArray.push(...linkData)
    },
    removeLinkElement(state, keysArr) {
      let linkDataArray = [...state.linkDataArray];
      let newLinkDataArray = [...state.linkDataArray];
      linkDataArray.forEach(
        (linkItem, i) => {
          keysArr.forEach(
            removeKey => {
              if (removeKey === linkItem.key) {
                newLinkDataArray.splice(i, 1);
              }
            }
          )
        }
      )
      console.log(newLinkDataArray)
      state.linkDataArray = newLinkDataArray;
    },
    removeElement(state, keysArr) {
      let nodeDataArray = [...state.nodeDataArray];
      let newNodeDataArray = [...state.nodeDataArray];
      nodeDataArray.forEach(
        (nodeItem, i) => {
          keysArr.forEach(
            removeKey => {
              if (removeKey === nodeItem.key) {
                newNodeDataArray.splice(i, 1);
              }
            }
          )
        }
      )
      console.log(newNodeDataArray)
      state.nodeDataArray = newNodeDataArray;
    },
    addLog(state, content) {
      let {operationLog, linkDataArray, nodeDataArray, modelData, selectedUUID, treeContent} = state;
      let pre = {...treeContent[selectedUUID]};
      treeContent[selectedUUID] = Object.assign(pre, {
        nodeDataArray,
        linkDataArray,
      })

      operationLog.unshift({
        time: moment().format('YYYY/MM/DD HH:mm:ss'),
        user: 'admin',
        operation: content,
      },)
    },
    openProperty(state, key) {
      //根据key中包含的组件名打开对应的属性设置侧边栏
      state.selectedNodeKey = key;
      let nodeTypeInfinitePowerSupply= key.includes('无穷大电源');
      let nodeTypePcs= key.includes('储能变流器');
      let nodeTypeEsBattery= key.includes('储能电池');
      let nodeTypeThreeWindingTransformer= key.includes('三绕组变压器');
      let nodeTypeAcBreaker= key.includes('交流断路器');
      let nodeTypeDcBreaker= key.includes('直流断路器');
      let nodeTypeEsAlternativeNode= key.includes('储能备选节点');
      let nodeTypeCrossPoint= key.includes('交叉点');
      let nodeTypeAcBus= key.includes('交流母线');
      let nodeTypeDcBus= key.includes('直流母线');


      if(nodeTypeInfinitePowerSupply == true) state.showPropertyInfinitePowerSupply = true;
      else if(nodeTypePcs == true) state.showPropertyPcs = true;
      else if(nodeTypeEsBattery == true) state.showPropertyEsBattery = true;
      else if(nodeTypeThreeWindingTransformer == true) state.showPropertyThreeWindingTransformer = true;
      else if(nodeTypeAcBreaker == true) state.showPropertyAcBreaker = true;
      else if(nodeTypeDcBreaker == true) state.showPropertyDcBreaker = true;
      else if(nodeTypeEsAlternativeNode == true) state.showPropertyEsAlternativeNode = true;
      else if(nodeTypeCrossPoint == true) state.showPropertyCrossPoint = true;
      else if(nodeTypeAcBus == true) state.showPropertyAcBus = true;
      else if(nodeTypeDcBus == true) state.showPropertyDcBus = true;


    },
    closeProperty(state, formItem) {
      const {selectedUUID, selectedNodeKey} = state;
      //属性设置页将属性设置值传回到属性结构体中
      state.nodeProperty[selectedUUID][selectedNodeKey] = formItem;
      state.selectedNodeKey = '';
      //所有的属性设置框都收回
      state.showProperty = false;
      state.showPropertyInfinitePowerSupply = false;
      state.showPropertyPcs = false;
      state.showPropertyEsBattery = false;
      state.showPropertyThreeWindingTransformer = false;
      state.showPropertyAcBreaker = false;
      state.showPropertyDcBreaker = false;
      state.showPropertyEsAlternativeNode = false;
      state.showPropertyCrossPoint = false;
      state.showPropertyAcBus = false;
      state.showPropertyDcBus = false;
    },
    openPlot(state) {
      state.configurationMode = 'plot';
    },
    closePlot(state) {
      state.configurationMode = 'index';
    },
    openThree(state) {
      state.configurationMode = 'three';
    },
    closeThree(state) {
      state.configurationMode = 'index';
    },
  },
  actions: {
    saveFile(context) {
      const {nodeDataArray, linkDataArray, selectedUUID, nodeProperty} = context.state;
      saveFileService({
        fileUUID: selectedUUID,
        nodeDataArray,
        linkDataArray,
        nodeProperty: {
          [selectedUUID]:
          nodeProperty[selectedUUID]
        }
      }).then(
        res => {
          console.log(res)
        }
      )
    },
    saveMatlabFile(context) {
      const {nodeDataArray, linkDataArray, selectedUUID, nodeProperty} = context.state;
      saveMatlabFileService({
        fileUUID: selectedUUID,
        nodeDataArray,
        linkDataArray,
        nodeProperty: {
          [selectedUUID]:
            nodeProperty[selectedUUID]
        }
      }).then(
        res => {
          console.log(res)
        }
      )
    },
  }
})
